/**
 * @param {*} options 
 */
var DataHandler = function(options){
    var t = this;
    t.options = $.parseJSON(JSON.stringify(options));
    t.$dom = $(options.container);
    this.$dom.html(DataHandler.tableTpl);
    t._init_event_();
    t._load_({
    	"userConditions":t.options.userConditions,
    	"size":20,
    	"page":1,
    	"needTotal":true
    });
}
/**
 * 重新加载
 */
DataHandler.prototype.reload = function(userConditions){
	var t = this;
	t.options.userConditions = userConditions
	t._load_({
    	"userConditions":t.options.userConditions,
    	"size":20,
    	"page":1,
    	"needTotal":true
    });
}
/**
 * 加载并渲染数据
 */
DataHandler.prototype._load_=function(params){
	var t = this;
	var options = t.options;
	params.designId = options.designId;
	cmp.dialog.loading();
	rptApi.getQueryResult({},params,{
		success:function(rs){
			if(!rs.success){
				DataHandler.alert(rs.msg);
				return;
			}
			var rdata = t._datas_ = rs.data;
			t.resetpostion();
			t._rendheader_(rdata.fields)
			t._displayFields_ = rdata.fields;
			t._datas_ = rdata.data;
			t._page_ = rdata.page;
			t._pages_ = rdata.pages;
			t._size_ = rdata.size;
			t._total_ = rdata.total;
			
			var dataLength = rdata.data.length;
			if(dataLength == 0){
				t.$dom.find(".qt-tb-no-data-warp").css("visibility","visible").find(".qt-tb-no-data-label").text(cmp.i18n("report.common.nodata"));
				t.$dom.find(".qt-tb-body tbody").html("");
				t.$dom.find(".qt-tb-footer .pages").html("-/-");
			}else{
				t.$dom.find(".qt-tb-no-data-warp").css("visibility","hidden");
				var header = "",
					dfsLength = t._displayFields_.length,
					serverAddr = cmp.serverIp ? cmp.serverIp : "";
				for (var index = 0; index < dataLength; index++) {
					var row = rdata.data[index];
					header += '<tr row-num="' + index + '" >';
					for(var j=0;j < dfsLength;j++){
						var df = t._displayFields_[j];
						var cellVal = row[j];
						var showValue = "";
						if(cellVal != null && cellVal != undefined){
							switch (df.fieldComType) {
								case "imageenum" :
									if(df.formatType == "showName"){
										showValue = DataHandler.toHtml(cellVal.v);
									}else{
										if(cellVal.v !== null){
											showValue = "<img class=\"image-value\" src=\"" + serverAddr + "/seeyon/fileUpload.do?method=showRTE&type=image&fileId=" + cellVal.v + "\">";
										}
									}
									break
								case "image" ://插入图片
									if(cellVal.v !== null){
										showValue = "<img class=\"image-value\" src=\"" + serverAddr + "/seeyon/fileUpload.do?method=showRTE&type=image&fileId=" + cellVal.v + "\">";
									}
									break;
								case "map" ://地图控件
								default:
									showValue = DataHandler.toHtml(cellVal.v);
									break;
							}
						}
						var styles = "";
						if(t._cellStyle_){
							styles += t._cellStyle_;
						}
						if(cellVal.css){
							styles += cellVal.css;
						}
						header += '<td ><div class="qt-tb-cell type-' + df.fieldComType+ '" style="' + styles + '">' + (showValue  ) + '</div></td>';
					}
					header += '</tr>';
				}
				t.$dom.find(".qt-tb-body tbody").html(header);
				t.$dom.find(".qt-tb-footer .pages").html(rdata.page + "/" + rdata.pages + cmp.i18n("report.common.page"));//"页");
			}
			cmp.dialog.loading(false);
		},
		error:function(error){
			cmp.dialog.loading(false);
			var cmpHandled = cmp.errorHandler(error);
			if (!cmpHandled) {
				if (error.message) {
					DataHandler.alert(error.message);
				} else {
					DataHandler.alert(cmp.toJSON(error));
				}
			}
		}
	});
}

DataHandler.prototype._rendheader_ = function(displayFields){
	var  wd = window.innerWidth,dflength = displayFields.length;
	if(dflength * 100 < wd){//当页无法撑开的时候设置固定的百分比
		this._cellStyle_ = "width:" + Math.floor(wd/dflength) + "px;";
	}
	//渲染表头
	var header = DataHandler.headTpl.render({
		displayFields:displayFields,
		"cellStyle":this._cellStyle_ ? this._cellStyle_ : ""
	});
	this.$dom.find(".qt-tb-header tbody").html(header);

}
/**
 * 初始化事件
 */
DataHandler.prototype._init_event_ = function(){
	var t = this;
	//穿透
	t.$dom.on(clickOrTap,".qt-tb-body tbody tr",function(){
		var rowIndex = $(this).attr("row-num");
		var rowData = t._datas_[rowIndex];
		if(!rowData.rcp){
			return;
		}
		if(t.options.isPreview){
			return;
		}
		cmp.dialog.loading();
		rptApi.getQueryPenetrate({},{
			"extendParams":JSON.stringify(rowData.rpp),
			"designId":t.options.designId
		},{
			success:function(rs){
				if(!rs.success){
					DataHandler.alert(rs.msg);
					return;
				}
				cmp.dialog.loading(false);
				var penetrateList = rs.data.penetrateList;
				if(penetrateList.length == 1){
					DataHandler._junp_to_(penetrateList[0],t.options.designId);
				}else{ 
					var formList = [];
					var plength = penetrateList.length;
					for (var int = 0; int < penetrateList.length; int++) {
						formList.push(penetrateList[int].formName);
					}
					formList.push(cmp.i18n("report.common.cancel"));
					cmp.notification.judge('选择穿透数据',function (index) {
						if(plength > index){// 除取消
							var info = penetrateList[index];
							DataHandler._junp_to_(info,t.options.designId);
						}
					},undefined, formList);
				}
				
			},
			error:function(es){
				cmp.dialog.loading(false);
				var cmpHandled = cmp.errorHandler(error);
				if (!cmpHandled) {
					if (error.message) {
						DataHandler.alert(error.message);
					} else {
						DataHandler.alert(cmp.toJSON(error));
					}
				}
			}
		});
	}).on(clickOrTap,".prePage",function(){//上一页
		var page = parseInt(t._page_) - 1;
		if(page > 0){
			t._load_({
				"userConditions":t.options.userConditions,
				"size":20,
				"page":page,
				"needTotal":true
			});
		}
	}).on(clickOrTap,".nextPage",function(){//下一页
		var page = parseInt(t._page_) + 1;
		if(page <= t._pages_){
			t._load_({
				"userConditions":t.options.userConditions,
				"size":20,
				"page":page,
				"needTotal":true
			});
		}
	}).on(clickOrTap,".pages",function(){//分页
	});

	t.totalX =0 ;
	t.totalY=0;
	var timer = null;
	var limitWidth = 0 , limitHeight = 0;
	var cw = $(window).width();
	t.$dom.on("touchstart",function(e){
		var start = e.changedTouches[0];
		startX = start.pageX;
		startY = start.pageY;
		limitWidth = cw - t.$dom.find(".qt-tb-header-table").width();
		limitHeight = t.$dom.find(".qt-tb-body").height() - t.$dom.find(".qt-tb-body-table").height();
	}).on("touchmove",function(e){
		if(timer !== null){
			clearTimeout(timer);
		}
		var move = e.changedTouches[0];
		timer = setTimeout(function(){
			var moveX = move.pageX;
			var moveY = move.pageY;
			var thisEndX = t.totalX - (startX - moveX);
			var thisEndY = t.totalY - (startY - moveY);
			if(thisEndX > 0){
				thisEndX =0;
			}else if(thisEndX < limitWidth){
				thisEndX = limitWidth;
			}
			if(thisEndY > 0  || limitHeight > 0){
				thisEndY =0;
			}else if(thisEndY < limitHeight ){
				thisEndY = limitHeight;
			}
			t.$dom.find(".qt-tb-header-table").css("transform","translateX(" + thisEndX + "px)");//x y
			t.$dom.find(".qt-tb-body-table").css("transform","translate(" + thisEndX + "px," +  thisEndY + "px)");//x y
		},10);//延期10ms 避免卡卡卡
	}).on("touchend",function(e){
		var move = e.changedTouches[0];
		var moveX = move.pageX;
		var moveY = move.pageY;
		t.totalX = t.totalX - (startX - moveX);
		t.totalY = t.totalY - (startY - moveY);
		if(t.totalX > 0){
			t.totalX = 0;
		}else if(t.totalX < limitWidth){
			t.totalX = limitWidth;
		}
		if(t.totalY > 0 || limitHeight > 0){
			t.totalY = 0;
		}else if(t.totalY < limitHeight){
			t.totalY = limitHeight;
		}
		t.$dom.find(".qt-tb-header-table").css("transform","translateX(" + t.totalX + "px)");//x y
		t.$dom.find(".qt-tb-body-table").css("transform","translate(" + t.totalX + "px," +  t.totalY + "px)");//x y
		if(timer !== null){
			clearTimeout(timer);
		}
	});
	
}
DataHandler.prototype.resetpostion=function(penetrateInfo,designId){
	this.totalX =0 ;
	this.totalY=0;
	this.$dom.find(".qt-tb-header-table").css("transform","translateX(0px)");//x y
	this.$dom.find(".qt-tb-body-table").css("transform","translate(0px,0px)");//x y
}


DataHandler._junp_to_=function(penetrateInfo,designId){
	switch (penetrateInfo.category) {
		case "form":
		{
			//com.seeyon.ctp.form.util.Enums.FormType
			if(penetrateInfo.formType == 1){//流程表单
				RptUtils.load_jscss([collaborationPath + "/collaboration_m_api.s3js" + buildversion],[],function(){
					collApi.openSummary({
						"summaryId":penetrateInfo.moduleId,
						"operationId":penetrateInfo.rightId,
						"formId":penetrateInfo.formId,
						"openFrom":"formQuery"
					});
				});
			}else if(penetrateInfo.formType == 2 || penetrateInfo.formType == 3){//无流程表单
				RptUtils.load_jscss([unflowformPath + "/unflowform_m_api.s3js" + buildversion],[],function(){
					cmp.openUnflowFormData({
						"moduleType":37,
						"moduleId":penetrateInfo.moduleId,
						"name":penetrateInfo.formName,
						"rightId":penetrateInfo.rightId,
						"viewState":2,
						"formId":penetrateInfo.formId,
						"needCheckRight":true//检查权限
					});
				});
			}else{
				cmp.notification.toast("sorry 暂不支持穿透","center");
			}
			break;
		}
		case "excelreport":
		{
			RptUtils.load_jscss([vreportPath + "/vreport_m_api.s3js" + buildversion],[],function(){
				var penetrateInfo1 = $.parseJSON(JSON.stringify(penetrateInfo));
				penetrateInfo1.designId = designId;
				vreportApi.viewExcelDetail(penetrateInfo1);
			});
			break;
		}
		case "cap4biz":
		case "cap4Form"://cap4
		{
			//com.seeyon.ctp.form.util.Enums.FormType
			if(penetrateInfo.formType == 1){//流程表单
				RptUtils.load_jscss([collaborationPath + "/collaboration_m_api.s3js" + buildversion],[],function(){
					collApi.openSummary({
						"summaryId":penetrateInfo.moduleId,
						"operationId":penetrateInfo.rightId,
						"formId":penetrateInfo.formId,
						"designId":designId,
						"openFrom":"capQuery"
					});
				});
			}else if(penetrateInfo.formType == 6){//无流程表单
				RptUtils.load_jscss([cap4Path + "/cap4_m_api.s3js"  + buildversion],[],function(){
					cap4Api.openUnFlow({
						formType:(penetrateInfo.includeLight ? "light" : "origin" ),// light | origin 表单类型
						type:"browse",// new | edit | browse 操作类型
						title:penetrateInfo.formName,
						params:{
							formTemplateId: penetrateInfo.formId,
							moduleId: penetrateInfo.moduleId,
							designId:designId,
							moduleType: "42",
							operateType:"2",//0 = 新建 1 = 编辑 2= 浏览
							rightId:penetrateInfo.rightId
						}
					},{
						openWebViewCatch:1
					});
				});
			}else{
				cmp.notification.toast("sorry 暂不支持穿透","center");
			}
			break;
		}
		default:
			cmp.notification.toast("sorry  暂不支持穿透","center");
			break;
	}
}

DataHandler.alert = function(tips){
	cmp.notification.alert(tips);
}
DataHandler.toHtml = function(a) {
	try {
		return a ? (a = a.replace(/&/g, "&amp;"),
		a = a.replace(/</g, "&lt;"),
		a = a.replace(/>/g, "&gt;"),
		a = a.replace(/\'/g, "&#039;"),
		a = a.replace(/"/g, "&#034;"),
		a = a.replace(/ /g, "&nbsp;"),
		a) : ""
	} catch (error) {
		console.log("toHtml",a);
		return "";
	}
}
DataHandler.headTpl = laytpl('\
<tr >\
{{#\
	for(var i=0;i<d.displayFields.length;i++){\
		var displayField = d.displayFields[i];\
}}\
	<td ><div class="qt-tb-cell type-{{=displayField.fieldComType }}" style="{{d.cellStyle}}">{{=displayField.display }}</div></td>\
{{#\
	}\
}}\
</tr>\
');

DataHandler.tableTpl = '\
<div class="qt-tb-ct">\
	<div class="qt-tb-header">\
		<table class="qt-tb-header-table">\
			<tbody></tbody>\
		</table>\
	</div>\
	<div class="qt-tb-body">\
		<table class="qt-tb-body-table">\
			<tbody></tbody>\
		</table>\
	</div>\
</div>\
<div class="qt-tb-footer">\
	<span class="prePage">\
		<span class="cmp-icon cmp-icon-back"></span>\
	</span>\
	<span class="pages">5/100</span>\
	<span class="nextPage">\
		<span class="cmp-icon cmp-icon-forward"></span>\
	<\span>\
</div>\
<div class="qt-tb-no-data-warp">\
	<div class="qt-tb-no-data"></div>\
	<div class="qt-tb-no-data-label"><!--暂无数据--></div>\
</div>';